package com.lcp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lcp.entity.HealthLecture;
import com.lcp.mapper.HealthLectureMapper;
import com.lcp.service.HealthLectureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HealthLectureServiceImpl implements HealthLectureService {

    @Autowired
    private HealthLectureMapper healthLectureMapper;

    @Override
    public HealthLecture getById(Long id) {
        return healthLectureMapper.selectById(id);
    }

    @Override
    public IPage<HealthLecture> page(Integer pageNum, Integer pageSize, String status, String keyword) {
        QueryWrapper<HealthLecture> wrapper = new QueryWrapper<>();
        
        if (StringUtils.hasText(status)) {
            wrapper.eq("status", status);
        }
        
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like("title", keyword)
                .or()
                .like("speaker", keyword)
                .or()
                .like("content", keyword));
        }
        
        wrapper.orderByDesc("lecture_time");
        
        return healthLectureMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
    }

    @Override
    @Transactional
    public HealthLecture create(HealthLecture lecture) {
        lecture.setCreateTime(LocalDateTime.now());
        lecture.setUpdateTime(LocalDateTime.now());
        lecture.setViewCount(0);
        lecture.setLikeCount(0);
        lecture.setCurrentParticipants(0);
        
        healthLectureMapper.insert(lecture);
        return lecture;
    }

    @Override
    @Transactional
    public HealthLecture update(HealthLecture lecture) {
        lecture.setUpdateTime(LocalDateTime.now());
        healthLectureMapper.updateById(lecture);
        return lecture;
    }

    @Override
    @Transactional
    public void delete(Long id) {
        healthLectureMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void incrementViewCount(Long id) {
        HealthLecture lecture = healthLectureMapper.selectById(id);
        if (lecture != null) {
            lecture.setViewCount(lecture.getViewCount() + 1);
            healthLectureMapper.updateById(lecture);
        }
    }

    @Override
    @Transactional
    public void incrementLikeCount(Long id) {
        HealthLecture lecture = healthLectureMapper.selectById(id);
        if (lecture != null) {
            lecture.setLikeCount(lecture.getLikeCount() + 1);
            healthLectureMapper.updateById(lecture);
        }
    }

    @Override
    @Transactional
    public void incrementParticipants(Long id) {
        HealthLecture lecture = healthLectureMapper.selectById(id);
        if (lecture != null) {
            lecture.setCurrentParticipants(lecture.getCurrentParticipants() + 1);
            healthLectureMapper.updateById(lecture);
        }
    }

    @Override
    @Transactional
    public void decrementParticipants(Long id) {
        HealthLecture lecture = healthLectureMapper.selectById(id);
        if (lecture != null && lecture.getCurrentParticipants() > 0) {
            lecture.setCurrentParticipants(lecture.getCurrentParticipants() - 1);
            healthLectureMapper.updateById(lecture);
        }
    }

    @Override
    public List<HealthLecture> getUpcomingLectures(Integer limit) {
        QueryWrapper<HealthLecture> wrapper = new QueryWrapper<>();
        wrapper.eq("status", "UPCOMING")
            .gt("lecture_time", LocalDateTime.now())
            .orderByAsc("lecture_time")
            .last("limit " + limit);
            
        return healthLectureMapper.selectList(wrapper);
    }

    @Override
    public List<HealthLecture> getOngoingLectures() {
        QueryWrapper<HealthLecture> wrapper = new QueryWrapper<>();
        wrapper.eq("status", "ONGOING")
            .orderByAsc("lecture_time");
            
        return healthLectureMapper.selectList(wrapper);
    }

    @Override
    public List<HealthLecture> getFinishedLectures(Integer limit) {
        QueryWrapper<HealthLecture> wrapper = new QueryWrapper<>();
        wrapper.eq("status", "FINISHED")
            .orderByDesc("lecture_time")
            .last("limit " + limit);
            
        return healthLectureMapper.selectList(wrapper);
    }

    @Override
    public Map<String, Object> getLectureStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        // 统计各状态的讲座数量
        QueryWrapper<HealthLecture> wrapper = new QueryWrapper<>();
        wrapper.select("status", "count(*) as count")
            .groupBy("status");
            
        List<Map<String, Object>> statusStats = healthLectureMapper.selectMaps(wrapper);
        statistics.put("statusStatistics", statusStats);
        
        // 统计总参与人数
        wrapper = new QueryWrapper<>();
        wrapper.select("sum(current_participants) as totalParticipants");
        Map<String, Object> participantStats = healthLectureMapper.selectMaps(wrapper).get(0);
        statistics.put("totalParticipants", participantStats.get("totalParticipants"));
        
        // 统计平均评分
        wrapper = new QueryWrapper<>();
        wrapper.select("avg(rating) as averageRating");
        Map<String, Object> ratingStats = healthLectureMapper.selectMaps(wrapper).get(0);
        statistics.put("averageRating", ratingStats.get("averageRating"));
        
        return statistics;
    }
} 